
/**
 * 视频广告  下一步
 */
 $(function(){  
	 //视频上传
	 initUpload();

	  //正则验证
	 function mustval(){ //非空验证
		 var adNameVal=$("#adName").val();
		 var mustVal=/^\S|\S$/;
		 if(mustVal.test(adNameVal)){
			 return true;
		 }else{
			 return false;
		 }
	 };
	 	//广告名称
		$("#adName").on("blur",function(){
			if(!$(this).val()){
				$("#mustVal").html("*必填").show();
			}else{
				$("#mustVal").hide();
			}
		});
		//广告链接
		$("#advUrl").on("blur",function(){
			if(!$(this).val()){
				$("#urlspan").html("*必填").show();
			}else{
				$("#urlspan").hide();
			}
		});
		//广告描述
		$("#description").on("blur",function(){
			if(!$(this).val()){
				$("#descriptspan").html("*必填").show();
			}else{
				$("#descriptspan").hide();
			}
		});
	  function keyletter(keyval){ //关键字
	 	  var patKey=/^[A-Za-z0-9\u4e00-\u9fa5]+$/;
	 	  if(patKey.test(keyval)){
	 		 return true;
	 	  }else{
	 		 return false;
	 	  } 
	  };
	  $("#keyPat").hide();
	  $("#keyPat2").hide();
	  $("#keyPat3").hide();
	  $("#keyPat4").hide();
	  $("#keyPat5").hide();
	  $("#keyPat6").hide();
	  
	  $("#key1").on("blur",function(){
		  var keyVal=$("#key1").val();
		  var result=keyletter(keyVal);
		  if(!$(this).val()){
		 	  $("#keyPat").html("*必填").css("right","-1px").show();
		  }else if(result){
		 	  $("#keyPat").hide();
		  }else{
		 	  $("#keyPat").html("*由中文、数字、英文组成").css("right","-125px").show();
		  }
	  });
	  $("#key2").on("blur",function(){
		  keyWordPattern($("#key2"),$("#keyPat2"));
	  });
	  $("#key3").on("blur",function(){
		  keyWordPattern($("#key3"),$("#keyPat3"));
	  });
	  $("#key4").on("blur",function(){
		  keyWordPattern($("#key4"),$("#keyPat4"));
	  });
	  $("#key5").on("blur",function(){
		  keyWordPattern($("#key5"),$("#keyPat5"));
	  });
	  $("#key6").on("blur",function(){
		  keyWordPattern($("#key6"),$("#keyPat6"));
	  });
	  function keyWordPattern(key,keypat){
		  var keyVal=key.val();
		  var result=keyletter(keyVal);
		  if(!key.val()){
			  keypat.hide();
		  }else if(result){
			  keypat.hide();
		  }else{
		      keypat.show();
		  }
	  }
	  
	  function keyPatFun(){
		 var keyPat2=$("#keyPat2").css("display");
		 var keyPat3=$("#keyPat3").css("display");
		 var keyPat4=$("#keyPat4").css("display");
		 var keyPat5=$("#keyPat5").css("display");
		 var keyPat6=$("#keyPat6").css("display");
		 if(keyPat2=="block" || keyPat3=="block" || keyPat4=="block" ||keyPat5=="block" ||keyPat6=="block" ){
			 return true;
		 }else{
			 return false;
		 }
	 }
	  
	  $("body").on("mouseover",function(){
		 var keyVal=$("#key1").val();
		 var Achecked=$(".adTargetModalBox img[data-target='1']");
		 if(Achecked.length!=0){
			 $(".targetAlert").hide();
		 }else{
			 $(".targetAlert").show();
		 }
		 /*var dataLoading=$(".uploadRateBar").css("display");*/
		  var dataLoading=$("#loadingFont").html();
		  var adHomeImage = $("#adHomeImage").attr("src"); //广告主页
		  var advUrl = $("#advUrl").val(); //广告链接
		 if(advUrl && adHomeImage && $("#adName").val() && $("#description").val()&& keyletter() && !keyPatFun(keyVal) && dataLoading=="上传完成！" && Achecked.length!=0){
			 $(".modifyImgSignBtn").attr("disabled",false);

		 }else{
			 $(".modifyImgSignBtn").attr("disabled",true);
		 }
	 });
	 $(".modifyImgSignBtn").on("click",function(){
		 saveVideoAd();
		 $(".modifyImgSignBtn").off();
	 });

 });

 //全局变量
 var videoUrl ="";//视频url
 var videoSize="";//视频大小
var adHomepage = "";//主页图片
 function saveVideoAd(){
 	var name = $("#adName").val();//广告名
 	var advUrl = $("#advUrl").val(); //广告链接
 	var description =  $("#description").val();//描述

 	var duration = $("#duration").html();//广告时长
 	var terminalType = "";//终端
 	//关键字
 	var adKey ="";
 	var key1 = $("#key1").val();
 	var key2 = $("#key2").val();
 	var key3 = $("#key3").val();
 	var key4 = $("#key4").val();
 	var key5 = $("#key5").val();
 	var key6 = $("#key6").val();
 	if(key1.length !=0 ){adKey += key1+"|";}
 	if(key2.length !=0 ){adKey += key2+"|";}
 	if(key3.length !=0 ){adKey += key3+"|";}
 	if(key4.length !=0 ){adKey += key4+"|";}
 	if(key5.length !=0 ){adKey += key5+"|";}
 	if(key6.length !=0 ){adKey += key6+"|";}
	 //广告属性
	 var adClassify = "";
	 var Achecked=$(".adTargetModalBox img[data-target='1']");
	 $.each(Achecked,function(index){
		 adClassify +=Achecked[index].id+"|";
	 });

	//广告视频
 	if(videoUrl.length==0){//没有上传广告
 		alert("请您上传广告视频！")
 		return 
 	}
 	/*console.log(adHomepage);*/
 	if(adHomepage.length !=-1){

		terminalType =  transitionFTerminalTyp($(".selectedUploaded span").html());//终端
		//提交更新
		$.ajax({
			url : '/web-adv/saveVideosAd',
			data:{
					name:name,
					advUrl:advUrl,
					description:description,
					adHomepage:adHomepage,
					adKey:adKey,
					terminalType:terminalType,
					videoUrl:videoUrl,
					videoSize:videoSize,
					duration:duration,
					adClassify:adClassify
				},
			type : 'post',
			success : function(data) {

				if(data.resultVo.status== '1'){
					var adCode = data.adCode;
					console.log("视频上传"+adCode);
					window.location.href="/web-adv/advWeb/views/uploadAd/videoAd/uploadCheck.html?selectedNav=1&navPos=1&adCode="+adCode;
				}else{
					alert("保存失败！");
				}

			},
			error: function(){}
		});
 	}else{
 		
 		alert("请您上传广告封面！");
 	}
 }

 var intId ;//window.setInterval对应的返回
 var loadingVideoUrl = null;
 function initUpload(){//上传视频
 	 //video_upload
 	new AjaxUpload($("#uploadVideo")[0],{
 		action:"/web-adv/uploadVideoAdFile",
 		name:'uploadVideo',
 		data:{},
 		onSubmit:function(file,extension){
 			extension=extension.toUpperCase();
 			//if(extension!="MOV"&&extension!="MP4"&&extension!="MPV"&&extension!="3GP"&&extension!="AVI"&&extension!="WMV"){
 			if(extension!="MP4"){
 				//alert("只支持视频MOV/MP4/MPV/3GP/AVI文件格式!");
 				alert("只支持视频MP4!");

 				return false;
 			}else{
 				//console.log(file);
 			 $(".uploadRateBar").toggleClass("hide show");
 			 $("#videoMsg").html(file);
 			 intId = window.setInterval("processShow()", 100);
 			}
 		},
 		onComplete:function(file,response){	
 			var dataObj=eval("("+response+")");//转换为json对象 
             if(dataObj){		
 			if(dataObj.status==1){
				videoUrl = dataObj.data;
				videoSize = dataObj.fileSize;
				loadingVideoUrl = dataObj.videoServerPrex+videoUrl;
				console.log(loadingVideoUrl);
			var showInfo = dataObj.showInfo;
 			 var time = showInfo.substring(showInfo.lastIndexOf('-')+1,showInfo.length);
 			 $("#duration").html(time);
 			 $("#videoUrl").val(dataObj.data);
 			}else{		   
 				alert("文件大小超过50M,请您重新上传！");
 				return null;
 			}
 			}else{
 		     alert("您上传的视频为空！");
 		 }
 		}			
 	});
 }	
 //视频上传进度
 var processShow = function() {
     //console.log("3333");
     $.ajax({
         type: 'POST',
         url: '/web-adv/getProgress',
         data: {},  
         dataType: 'json',  
         success: function(data) {
         	if(!$("#videoLength").text()){       		
         		$("#videoLength").text(data.totalLength);
         	}
         	//console.log(data.totalLength);
             //console.log(data.rate);
 			 var loadingBar = data.rate+"%";
 			 $(".uploadRateBarBox").find("span").width(loadingBar);
 			 $("#loadingFont").text(loadingBar);
                     if (data.rate == 100) {
                        //上传成功，结束轮询
                     	window.clearInterval(intId);
                     	//alert("上传成功");
 						$("#loadingFont").text("上传完成！");
 						$(".modifyImgSignBtn").attr("data-loading","1");
 						$("[name='uploadVideo']").eq(1).attr("disabled","disabled");
                      }
         }
     });
  };
  //删除视频
  var delVideo = function(){
      $(".modifyImgSignBtn").attr("data-loading","0");
      $("#videoLength").text("");
 	 $(".uploadRateBar").toggleClass("show hide");
 	 $(".uploadRateBarBox").find("span").width("0%");
 	 $("#loadingFont").text("0%");
 	 $("[name='uploadVideo']").eq(1).removeAttr("disabled");
 	 $("#duration").html("");
  }

//base 64转为blob
function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {type: mimeString});
}

$(".uploadNav ul").find("li").click(function(){
	$(this).addClass("selectedUploaded");
	$(this).siblings("li").removeClass("selectedUploaded");
});

var uploadImg = {
	change:function(e,ele){
		var fs = new FileReader(),files = e.files[0];
		fs.readAsDataURL(files);
		fs.onload = function(event){
			if(ele.parent().next().find('li').length>8){
				alert("最多只能9张图片，请先删除不需要的图片后再上传")
			}else{
				var html = '<li><span onclick="uploadImg.delegate($(this))">X</span>'+
					'<img src="'+this.result+'" alt="" />'+
					'</li>';
				ele.parent().next().append(html);
			}
		}
	},
	changeHomeImage:function(e,ele){
		var fs = new FileReader(),files = e.files[0];
		var fileName = files.name;
		if(files.size>10*1024*1024 ||files.size<10*1024 ){
			console.log("======封面====="+files.size)
			alert("单照图片在10K-10M之间，请您重新选择图片！");
		}else {
			if(!uploadImg.isSuffix(fileName)) return false;//判断图片格式
			fs.readAsDataURL(files);
			fs.onload = function (event) {
				//console.log(ele.parent("div.uploadBtnBg").siblings("img").length);
				ele.parent("div.uploadBtnBg").siblings("img").attr("src", this.result);

				//上传封面
				var fd = new FormData();
				var blob = dataURItoBlob(this.result);
				fd.append('file', blob,fileName);
				$.ajax({
					url : '/web-adv/uploadImgs',
					type : 'post',
					data:fd,
					processData: false, // 不会将 data 参数序列化字符串
					contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
					success : function(data) {
						var data=JSON.parse(data);
						//console.log(data.data)
						if(data.status=="1"){
							//保存 所有
							adHomepage = data.data;
						}else{
							alert("保存失败！");
						}
					},
					error: function(){}
				});
			}
		}
	},
	delegate:function(ele){
		ele.parent().remove();
	},
	toggleNav:function(ele){

		ele.addClass("selectedUploaded");
		ele.siblings("li").removeClass("selectedUploaded");
	},
	isSuffix:function(ele){
		ele = ele.substring(ele.lastIndexOf(".")+1,ele.length);
		ele=ele.toUpperCase();//jpg、gif、png
		if(ele!="PNG"&&ele!="GIF"&&ele!="JPEG"&&ele!="JPG"){
			alert("请您上传jpg、gif、png格式的图片！")
			return false;
		}

		return true;
	}
};
$(".uploadNav ul").find("li").click(function(){
	uploadImg.toggleNav($(this));
});